package com.xlh.aop;

import com.xlh.lock.KeyLock;
import com.xlh.util.AnnotationResolver;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 方法执行完后解锁
 *
 * @author cheer
 */
@Aspect
@Component
public class UnlockAspect {

    @Autowired
    private KeyLock<String> lock;

    @After("@annotation(PreAcquireLock)")
    public void unlock(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        PreAcquireLock preAcquireLock = method.getAnnotation(PreAcquireLock.class);

        String key = AnnotationResolver.resolver(joinPoint, preAcquireLock.value());

        lock.unlock(key);
    }
}
